﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using Happy.Archetype;
using Happy.Domain;
using Happy.Cms.Domain.Shares;

namespace Happy.Cms.Domain.Articles
{
    [DomainModel, Moment]
    public class Article : AggregateRoot<Guid>
    {
        private ICollection<AssignedTag> _assignedTags = new List<AssignedTag>();

        protected Article()
        {
        }

        public Article(Guid id)
            : base(id)
        {
            this.SettingInfo = new SettingInfo();
            this.ImageInfo = new ImageInfo();
            this.SeoInfo = new SeoInfo();
        }

        public string Title { get; set; }

        public Guid CategoryId { get; set; }

        public string Author { get; set; }

        public ImageInfo ImageInfo { get; private set; }

        public SettingInfo SettingInfo { get; private set; }

        protected internal virtual ICollection<AssignedTag> AssignedTags
        {
            get { return _assignedTags; }
        }

        public string Content { get; set; }

        public DateTime? PublishDate { get; set; }

        public SeoInfo SeoInfo { get; private set; }

        public int Order { get; set; }

        public void AssignTags(IEnumerable<Guid> tagIds)
        {
            var newTagIds = tagIds == null ? Enumerable.Empty<Guid>() : tagIds.Distinct();

            var oldTagIds = this.AssignedTags.Select(x => x.TagId).ToList();
            var addedTagIds = newTagIds.Except(oldTagIds);
            var removedTagIds = oldTagIds.Except(newTagIds);

            foreach (var addedTagId in addedTagIds)
            {
                this.AssignedTags.Add(new AssignedTag(Guid.NewGuid(), addedTagId));
            }

            foreach (var removedTagId in removedTagIds)
            {
                this.AssignedTags.Remove(this.AssignedTags.First(x => x.TagId == removedTagId));
            }
        }
    }
}
